package com.laisheng.interview.controller;

import com.laisheng.interview.model.AccountingInfo;
import com.laisheng.interview.model.DevelopmentExercises;
import com.laisheng.interview.model.Notification;
import com.laisheng.interview.model.ResumeFile;
import com.laisheng.interview.service.impl.AccountingServiceImpl;
import com.laisheng.interview.service.impl.ExerciseServiceImpl;
import com.laisheng.interview.service.NotificationService;
import com.laisheng.interview.service.ResumeFileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 管理员控制器，处理面试管理系统的后台API请求
 */
@RestController
@CrossOrigin(origins = "*")
public class AdminController {
    @Autowired
    private AccountingServiceImpl accountingServiceImpl;

    @Autowired
    private ExerciseServiceImpl exerciseServiceImpl;
    
    @Autowired
    private NotificationService notificationService;
    
    @Autowired
    private ResumeFileService resumeFileService;


    // 获取单个用户详细数据
    /**
     * 根据ID获取单个面试者的详细信息
     * @param id 面试者ID
     * @return 面试者详细信息
     */
    @GetMapping("/api/accounting/data/{id}")
    public AccountingInfo getAccountingDataById(@PathVariable Long id) {
        return accountingServiceImpl.getAccountingInfoById(id);
    }
    
    /**
     * 标记面试者通过状态
     * @param id 面试者ID
     * @return 操作结果
     */
    @PostMapping("/api/accounting/markPassed/{id}")
    public Map<String, Object> markAsPassed(@PathVariable Long id) {
        Map<String, Object> response = new HashMap<>();
        try {
            accountingServiceImpl.markAsPassed(id, true);
            response.put("success", true);
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", e.getMessage());
        }
        return response;
    }

    // 获取用户的练习题数据
    @GetMapping("/api/exercises/data")
    public List<DevelopmentExercises> getExercisesByAccountingId(@RequestParam Long accountingId) {
        return exerciseServiceImpl.getExercisesByAccountingId(accountingId);
    }

    // 获取所有通知（支持按日期搜索）
    @GetMapping("/api/notifications")
    public List<Notification> getAllNotifications(@RequestParam(required = false) String date) {
        if (date != null && !date.trim().isEmpty()) {
            return notificationService.getNotificationsByDate(date);
        }
        return notificationService.getAllNotifications();
    }

    // 获取未读通知
    @GetMapping("/api/notifications/unread")
    public List<Notification> getUnreadNotifications() {
        return notificationService.getUnreadNotifications();
    }

    // 获取未读通知数量
    @GetMapping("/api/notifications/unread/count")
    public Map<String, Object> getUnreadCount() {
        Map<String, Object> response = new HashMap<>();
        response.put("count", notificationService.getUnreadCount());
        return response;
    }

    // 标记通知为已读
    @PostMapping("/api/notifications/{id}/read")
    public Map<String, Object> markAsRead(@PathVariable Long id) {
        Map<String, Object> response = new HashMap<>();
        try {
            notificationService.markAsRead(id);
            response.put("success", true);
            response.put("message", "标记成功");
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", e.getMessage());
        }
        return response;
    }
    
    // 批量标记通知为已读
    @PostMapping("/api/notifications/batch-read")
    public Map<String, Object> markMultipleAsRead(@RequestBody Map<String, Object> request) {
        Map<String, Object> response = new HashMap<>();
        try {
            @SuppressWarnings("unchecked")
            List<Long> ids = (List<Long>) request.get("ids");
            notificationService.markMultipleAsRead(ids);
            response.put("success", true);
            response.put("message", "批量标记成功");
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", e.getMessage());
        }
        return response;
    }
    
    // 标记所有通知为已读
    @PostMapping("/api/notifications/all-read")
    public Map<String, Object> markAllAsRead() {
        Map<String, Object> response = new HashMap<>();
        try {
            notificationService.markAllAsRead();
            response.put("success", true);
            response.put("message", "全部标记成功");
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", e.getMessage());
        }
        return response;
    }

    // 获取单个通知信息
    @GetMapping("/api/notifications/{id}")
    public Map<String, Object> getNotificationById(@PathVariable Long id) {
        Map<String, Object> response = new HashMap<>();
        try {
            List<Notification> notifications = notificationService.getAllNotifications();
            Notification notification = notifications.stream()
                    .filter(n -> n.getId().equals(id))
                    .findFirst()
                    .orElse(null);
            
            if (notification != null) {
                response.put("success", true);
                response.put("data", notification);
            } else {
                response.put("success", false);
                response.put("message", "通知不存在");
            }
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", e.getMessage());
        }
        return response;
    }

    // 获取简历文件信息
    @GetMapping("/api/resume/{accountingInfoId}")
    public Map<String, Object> getResumeByAccountingId(@PathVariable Long accountingInfoId) {
        Map<String, Object> response = new HashMap<>();
        try {
            ResumeFile resumeFile = resumeFileService.getByAccountingInfoId(accountingInfoId);
            if (resumeFile != null) {
                response.put("success", true);
                response.put("data", resumeFile);
            } else {
                response.put("success", false);
                response.put("message", "简历文件不存在");
            }
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", e.getMessage());
        }
        return response;
    }

    // 下载简历文件
    @GetMapping("/api/resume/download/{id}")
    public ResponseEntity<byte[]> downloadResume(@PathVariable Long id) {
        try {
            ResumeFile resumeFile = resumeFileService.getById(id);
            byte[] fileContent = resumeFileService.downloadResume(id);
            
            return ResponseEntity.ok()
                    .header("Content-Disposition", "attachment; filename=\"" + resumeFile.getOriginalFileName() + "\"")
                    .header("Content-Type", resumeFile.getFileType())
                    .body(fileContent);
        } catch (Exception e) {
            return ResponseEntity.notFound().build();
        }
    }

    // 获取简历内容
    @GetMapping("/api/resume/content/{id}")
    public Map<String, Object> getResumeContent(@PathVariable Long id) {
        Map<String, Object> response = new HashMap<>();
        try {
            ResumeFile resumeFile = resumeFileService.getById(id);
            if (resumeFile == null) {
                response.put("success", false);
                response.put("message", "简历文件不存在");
                return response;
            }
            
            byte[] fileContent = resumeFileService.downloadResume(id);
            if (fileContent == null || fileContent.length == 0) {
                response.put("success", false);
                response.put("message", "简历文件内容为空");
                return response;
            }
            
            // 如果是PDF文件，返回Base64编码的内容用于前端直接显示
            if (resumeFile.getFileType().toLowerCase().contains("pdf")) {
                String base64Content = java.util.Base64.getEncoder().encodeToString(fileContent);
                response.put("success", true);
                response.put("data", Map.of(
                    "content", base64Content,
                    "fileName", resumeFile.getOriginalFileName(),
                    "fileType", resumeFile.getFileType(),
                    "isPdf", true
                ));
            } else {
                // 对于其他文件类型，尝试转换为文本
                String content = new String(fileContent, StandardCharsets.UTF_8);
                response.put("success", true);
                response.put("data", Map.of(
                    "content", content,
                    "fileName", resumeFile.getOriginalFileName(),
                    "fileType", resumeFile.getFileType(),
                    "isPdf", false
                ));
            }
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "获取简历内容失败: " + e.getMessage());
        }
        return response;
    }

}